#include "MinPositionMatrix.h"
#include <vector>
#include <iostream>

using namespace std;


MinPositionMatrix::MinPositionMatrix(uint n, vector<uint> firstPositions)
:numPalavras(n),
 min(-1)
{
	positionMatrix = new uint * [numPalavras];
	for (uint i = 0; i < numPalavras; i++) {
		positionMatrix[i] = new uint[numPalavras];
		for (uint j = 0; j < numPalavras; j++)
			if (j != i)
				positionMatrix[i][j] = 0;
		positionMatrix[i][i] = firstPositions[i];
	}
}

MinPositionMatrix::~MinPositionMatrix()
{
	for (uint i = 0; i < numPalavras; i++)
		delete positionMatrix[i];
	delete positionMatrix;
}

void MinPositionMatrix::updateWithPosition(uint absolutePosition, uint index) {
	for (uint i = 0; i < numPalavras; i++) {
		//atualiza a ultima ocorrencia da palavra em questao
		if (i == index) 
			updateEq(absolutePosition, i);
		//atualiza ocorrencia para outras palavras
		else if (positionMatrix[i][index] == 0)
			updateDiff(absolutePosition, i, index);
	}
}

void MinPositionMatrix::updateEq(uint absolutePosition, uint i) {
	for (uint j = 0; j < numPalavras; j++) {
		if (i != j)
			positionMatrix[i][j] = 0;
	}
	positionMatrix[i][i] = absolutePosition;
}

void MinPositionMatrix::updateDiff(uint absolutePosition, uint i, uint index) {
	if (absolutePosition > positionMatrix[i][i]) {
		positionMatrix[i][index] = absolutePosition - positionMatrix[i][i];
		if (isComplete(i)) {
//			cout << "maxOff: "<< getMaxOffset(i); 
			if (min > getMaxOffset(i) + 1)
				min = getMaxOffset(i) + 1;
//			cout << "\tmin: " << min << endl;
			cleanPosition(i);
		}
	}
}

bool MinPositionMatrix::isComplete(uint pos) {
	for (uint j = 0; j < numPalavras; j++)
		if (j != pos && positionMatrix[pos][j] == 0)
			return false;
	return true;
}

uint MinPositionMatrix::getMaxOffset(uint pos) {
	uint max = 0;
	for (uint j = 0; j < numPalavras; j++)
		if (j != pos && positionMatrix[pos][j] > max)
			max = positionMatrix[pos][j];
	return max;
}

void MinPositionMatrix::cleanPosition(uint pos) {
	for (uint j = 0; j < numPalavras; j++)
		if (j != pos)
			positionMatrix[pos][j] = 0;
}

void MinPositionMatrix::showMatrix() {
	for (uint j = 0; j < numPalavras; j++) {
		for (uint k = 0; k < numPalavras; k++) 
			cout << positionMatrix[j][k] << " ";
		cout << endl;
	}
}
